
package com.hmsg.health.controller;


import com.hmsg.health.bean.vo.*;
import com.hmsg.health.dao.TaskTypeDao;
import com.hmsg.health.service.MenWangSMSService;
import com.hmsg.health.service.TaskService;
import com.hmsg.health.service.UserService;
import com.hmsg.health.service.aes.SecurityData;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hmsg.health.bean.domain.TaskDo;
import com.hmsg.health.bean.domain.TaskTypeDo;
import com.hmsg.health.bean.domain.UserAccountDo;
import com.hmsg.health.bean.domain.UserAccountRecordDo;
import com.hmsg.health.bean.domain.UserTaskDo;
import com.hmsg.health.bean.enums.StatusCode;
import com.hmsg.health.config.Constants;
import com.hmsg.health.config.PropertyConfig;
import com.hmsg.health.param.ResponseResult;
import com.hmsg.health.security.IgnoreSecurity;
import com.hmsg.health.security.OpenApi;
import com.hmsg.health.security.TokenManager;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Author Tareva on 2018/11/11.
 * @Description TODO
 */
@Api(value = "任务相关", tags = { "任务相关" })
@Slf4j
@Controller
@RequestMapping("/task")
public class TaskController {

    @Autowired
	StringRedisTemplate stringTemplate;
    @Autowired
  	private MenWangSMSService smsService;
	@Autowired
	private TokenManager tokenManager;
    static final String XCODE_KEY = "XCODE_KEY_";
    @Autowired
  	PropertyConfig propertyConfig;
    @Autowired
    private UserService userService;
    @Autowired
    private TaskService taskService;
    
    @Autowired
    private TaskTypeDao taskTypeDao;

    @PostMapping("/tasks")
    @ApiOperation(value="任务列表", notes="任务列表" ,httpMethod="POST")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	@ApiImplicitParams({
   		@ApiImplicitParam(name="type", value="任务类型  1拼多多砍价 2拼多多现金 3其他", dataType = "number", required=false, paramType="form"),
   		@ApiImplicitParam(name="isRecommend", value="任务类型  1拼多多砍价 2拼多多现金 3其他", dataType = "number", required=false, paramType="form")
   	})
    @SecurityData
	public  ResponseResult<List<TaskDo>> tasks(@RequestHeader(Constants.CLIENT_USER) Integer userId,@RequestBody @Validated TaskVo vo) {
    	TaskDo task = new TaskDo();
    	
    	if(vo.getPageNo()!=null){
			Integer startNo = (vo.getPageNo()-1)*vo.getPageSize();
			task.setStartNo(startNo);
			task.setPageSize(vo.getPageSize());
		}
    	if(vo.getType()!=null&&vo.getType()!=0){
			task.setType(vo.getType());
		}
    	if(vo.getIsRecommend()!=null){
			task.setIsRecommend(vo.getIsRecommend());
		}
    	
    	if(vo.getIsHot()!=null){
			task.setIsHot(vo.getIsHot());
		}
    	task.setTaskStatus(0);
    	task.setSurplusCount(0);
    	task.setSortCloum(" t.is_recommend desc,t.id desc");
    	List<TaskDo> tasks = taskService.select(task);
    	if(tasks!=null&&tasks.size()>0){
    		for(TaskDo t:tasks){
    			
    			if(t.getTypeDo()!=null){
    				TaskTypeDo tt = new TaskTypeDo();
    				tt.setId(t.getTypeDo().getParentId());
    				List<TaskTypeDo> tts = taskTypeDao.select(tt);
    				if(tts!=null&&tts.size()>0){
    					t.getTypeDo().setParentType(tts.get(0));
    				}
    			}else{
    				TaskTypeDo tt = new TaskTypeDo();
    				tt.setId(-1);
    				//tt.setName(name);
    				t.setTypeDo(tt);
    			}
    			if(userId!=null&&userId!=0){
    				UserTaskDo ut = new UserTaskDo();
    				ut.setTaskId(t.getId());
    				ut.setUserId(userId);
    				List<UserTaskDo> uts = userService.selectUserTask(ut);
    				if(uts!=null&&uts.size()>0){
    					t.setIsApply(1);
    					t.setUserTaskStatus(uts.get(0).getStatus());
    				}else{
    					t.setIsApply(0);
    				}
    			}
    		}
    	}
		return new ResponseResult<List<TaskDo>>(StatusCode.SYSTEM_SUCCESS, tasks);
	}
    
    
    @GetMapping("/changeTask")
    @ApiOperation(value="换一个", notes="换一个" ,httpMethod="GET")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	@ApiImplicitParams({
   		@ApiImplicitParam(name="taskId", value="上一个任务ID", dataType = "number", required=false, paramType="form")
   	})
    @SecurityData
	public  ResponseResult<TaskDo> changeTask(@RequestHeader(Constants.CLIENT_USER) Integer userId,Integer taskId) {
    	
    	List<TaskDo> tasks = taskService.selectNot(taskId);
    	
    	List<TaskDo> res1 = new ArrayList<TaskDo>();
    	if(tasks!=null&&tasks.size()>0){
    		for(TaskDo t:tasks){
    			
    			boolean f = false;
    			if(t.getTypeDo()!=null){
    				TaskTypeDo tt = new TaskTypeDo();
    				tt.setId(t.getTypeDo().getParentId());
    				List<TaskTypeDo> tts = taskTypeDao.select(tt);
    				if(tts!=null&&tts.size()>0){
    					t.getTypeDo().setParentType(tts.get(0));
    				}
    			}else{
    				TaskTypeDo tt = new TaskTypeDo();
    				tt.setId(-1);
    				t.setTypeDo(tt);
    			}
    			UserTaskDo pa = new UserTaskDo();
    			pa.setTaskId(t.getId());
    			List<UserTaskDo> uts = userService.findAllUserTask(pa);
    			if(uts!=null&&uts.size()>0){
    				for(UserTaskDo ut:uts){
    					if(ut.getUser().getId()==userId){
    						f = true;
    					}
    					
    				}
    			}
    			
    			if(f==false){
    				res1.add(t);
    			}
    			
    		}
    		TaskDo t = new TaskDo();
    		if(res1.size()<=1) {
    			t = res1.get(0);
    		}else {
    			int res = getRandom(0,res1.size()-1);
        		t = res1.get(res);
    		}
    		
    		if(userId!=null&&userId!=0){
				UserTaskDo ut = new UserTaskDo();
				ut.setTaskId(t.getId());
				ut.setUserId(userId);
				List<UserTaskDo> uts = userService.selectUserTask(ut);
				if(uts!=null&&uts.size()>0){
					t.setIsApply(1);
					t.setUserTaskStatus(uts.get(0).getStatus());
				}else{
					t.setIsApply(0);
				}
			}
    		
    		return new ResponseResult<TaskDo>(StatusCode.SYSTEM_SUCCESS, t);
    	}else{
    		return new ResponseResult<TaskDo>(StatusCode.TASK_NULL, null);
    	}
		
	}
	
	public int  getRandom(int min, int max){
	    Random random = new Random();
	    int s = random.nextInt(max) % (max - min + 1) + min;
	    return s;

	}
    
    @GetMapping("/taskDetail")
    @ApiOperation(value="任务详情", notes="任务详情" ,httpMethod="GET")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	@SecurityData
	public  ResponseResult<TaskDo> taskDetail(@RequestHeader(Constants.CLIENT_USER) Integer userId,Integer taskId) {
    	try {
    		
        	TaskDo task = taskService.findOne(taskId);
        	if(task.getTypeDo()!=null){
				TaskTypeDo tt = new TaskTypeDo();
				tt.setId(task.getTypeDo().getParentId());
				List<TaskTypeDo> tts = taskTypeDao.select(tt);
				if(tts!=null&&tts.size()>0){
					task.getTypeDo().setParentType(tts.get(0));
				}
			}else{
				TaskTypeDo tt = new TaskTypeDo();
				tt.setId(-1);
				task.setTypeDo(tt);
			}
    		if(userId!=null&&userId!=0){
				UserTaskDo ut = new UserTaskDo();
				ut.setTaskId(task.getId());
				ut.setUserId(userId);
				List<UserTaskDo> uts = userService.selectUserTask(ut);
				if(uts!=null&&uts.size()>0){
					task.setIsApply(1);
					task.setUserTaskStatus(uts.get(0).getStatus());
					task.setVerifyDetail(uts.get(0).getVerifyDetail());
				}else{
					task.setIsApply(0);
				}
			}
    		return new ResponseResult<TaskDo>(StatusCode.SYSTEM_SUCCESS, task);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<TaskDo>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
    
    @PostMapping("/editTask")
    @ApiOperation(value="更新任务", notes="更新任务" ,httpMethod="POST")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	@SecurityData
	public  ResponseResult<TaskDo> editTask(@RequestHeader(Constants.CLIENT_USER) Integer userId,@RequestBody @Validated UpdateTaskVo vo) {
    	try {
    		UserAccountDo ua = userService.findUserAccountByUserId(userId);
        	TaskDo task = taskService.findOne(vo.getId());
        	if(task.getTaskStatus()==-1){
        		return new ResponseResult<TaskDo>(StatusCode.TASK_STATUS_ERROR, null);
        	}
        	if(vo.getStatus()!=null){
        		UserTaskDo ut = new UserTaskDo();
        		ut.setTaskId(task.getId());
        		ut.setStatus(1);
        		List<UserTaskDo> list = userService.findAllUserTask(ut);
        		if(list!=null&&list.size()>0){
        			for(UserTaskDo usertask:list){
        				usertask.setStatus(3);
        				userService.updateUserTask(usertask);
        				
        				UserAccountDo ua1 = userService.findUserAccountByUserId(usertask.getUser().getId());
        				
        				ua1.setGlod(ua1.getGlod()+task.getTaskGold());
        				
        				userService.updateUserAccount(ua1);
        				
        				UserAccountRecordDo uar = new UserAccountRecordDo();
        				uar.setAmount(task.getTaskGold());
        				uar.setCreateTime(new Date());
        				uar.setGlodType(1);
        				uar.setTitle("完成任务");
        				uar.setUserId(usertask.getUser().getId());
        				uar.setType(3);
        				userService.saveAccountRecord(uar);
        			}
        		}
        		
        		if(task.getSurplusCount()>0){
        			ua.setGlod(task.getTaskGold()*task.getSurplusCount()+ua.getGlod());
            		userService.updateUserAccount(ua);
        		}
        	
        		task.setTaskStatus(vo.getStatus());
        	}
        	if(vo.getIsRecommend()!=null){
        		
        		if(ua!=null){
        			if(ua.getGlod()!=null&&ua.getGlod()<1000){
        				return new ResponseResult<TaskDo>(StatusCode.USER_ACCOUNT_NOT_ENOUGH, null);
        			}else if(ua.getGlod()!=null&&ua.getGlod()>=1000){
        				ua.setGlod(ua.getGlod()-1000);
        				userService.updateUserAccount(ua);
        				
        				UserAccountRecordDo uar = new UserAccountRecordDo();
        				uar.setAmount(1000);
        				uar.setCreateTime(new Date());
        				uar.setGlodType(2);
        				uar.setTitle("置顶任务");
        				uar.setType(10);
        				uar.setUserId(userId);
        				userService.saveAccountRecord(uar);
        			}else{
        				return new ResponseResult<TaskDo>(StatusCode.USER_ACCOUNT_NOT_ENOUGH, null);
        			}
        			
        		}
        		task.setIsRecommend(vo.getIsRecommend());
        	}
        	taskService.update(task);
    		return new ResponseResult<TaskDo>(StatusCode.SYSTEM_SUCCESS, null);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<TaskDo>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
    @GetMapping("/taskTypes")
    @ApiOperation(value="任务类型", notes="任务类型" ,httpMethod="GET")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	@SecurityData
	public  ResponseResult<List<TaskTypeDo>> taskTypes() {
    	try { 
        	List<TaskTypeDo> task = taskTypeDao.findQuery();
        	if(task!=null&&task.size()>0){
        		for(TaskTypeDo t:task){
        			List<TaskTypeDo> seconds = taskTypeDao.selectByParentId(t.getId());
        			if(seconds!=null){
        				t.setSeconds(seconds);
        			}
        		}
        	}
    		return new ResponseResult<List<TaskTypeDo>>(StatusCode.SYSTEM_SUCCESS, task);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<List<TaskTypeDo>>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
    
    @GetMapping("/secondTypes")
    @ApiOperation(value="任务类型", notes="任务类型" ,httpMethod="GET")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	@SecurityData
	public  ResponseResult<List<TaskTypeDo>> secondTypes() {
    	try { 
        	List<TaskTypeDo> task = taskTypeDao.selectByParentIdIsNot();
    		return new ResponseResult<List<TaskTypeDo>>(StatusCode.SYSTEM_SUCCESS, task);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<List<TaskTypeDo>>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
    @GetMapping("/delTask")
    @ApiOperation(value="放弃任务", notes="放弃任务" ,httpMethod="GET")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	@SecurityData
	public  ResponseResult<Object> delTask(@RequestHeader(Constants.CLIENT_USER) Integer userId,Integer id) {
    	try {
    		
    		UserTaskDo uT = userService.findOneUserTask(id);
    		TaskDo ta = taskService.findOne(uT.getTaskId());
    		Integer res = userService.delUserTask(id);
    		if(res>0){
    			ta.setSurplusCount(ta.getSurplusCount()+1);
    			taskService.update(ta);
    		}
    		
    		return new ResponseResult<Object>(StatusCode.SYSTEM_SUCCESS, res);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<Object>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
    @GetMapping("/userTasks")
    @ApiOperation(value="指定任务下的所有用户领取的任务", notes="指定任务下的所有用户领取的任务" ,httpMethod="GET")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	@ApiImplicitParams({
   		@ApiImplicitParam(name="status", value="任务状态 1待审核  2审核未通过 3已完成 4纠纷单", dataType = "number", required=false, paramType="form"),
   		@ApiImplicitParam(name="taskId", value="任务Id", dataType = "number", required=false, paramType="form")
   	})
    @SecurityData
	public  ResponseResult<List<UserTaskDo>> userTasks(@RequestHeader(Constants.CLIENT_USER) Integer userId,Integer taskId,Integer status) {
    	try {
    		
    		UserTaskDo ut = new UserTaskDo();
    		ut.setTaskId(taskId);
    		ut.setStatus(status);
        	List<UserTaskDo> list = userService.selectUserTask(ut);
    		return new ResponseResult<List<UserTaskDo>>(StatusCode.SYSTEM_SUCCESS, list);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<List<UserTaskDo>>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
  
	
}

